package com.mars.component.scheduler.service.impl;

import java.util.Arrays;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mars.component.scheduler.constant.SchedulerConst;
import com.mars.component.scheduler.entity.SchedulerTask;
import com.mars.component.scheduler.mapper.SchedulerTaskMapper;
import com.mars.component.scheduler.service.SchedulerTaskService;
import com.mars.component.scheduler.utlis.SchedulerUtils;
import com.mars.service.support.BaseService;

@Service
public class SchedulerTaskServiceImpl extends BaseService<SchedulerTask, Long> implements SchedulerTaskService {
	
	@Autowired
	private SchedulerUtils schedulerUtils ;
	
	@Autowired
	private SchedulerTaskMapper mapper ;
	
	@Transactional
	@Override
	public void createScheduleJob(SchedulerTask task) {
		//保存任务信息到数据库
		super.insertSelective(task) ;
		
		this.schedulerUtils.createScheduleJob4Spring(task);
	}
	
	@Transactional
	@Override
	public void rescheduleJob(SchedulerTask task) {
		this.schedulerUtils.rescheduleJob(task);
		//修改数据库表中的数据
		super.updateSelective(task);
	}
	
	@Transactional
	@Override
	public void pause(Long[] jobIds, String[] groups) {
		for(int i=0; i<jobIds.length; i++) {
			SchedulerTask task = new SchedulerTask(jobIds[i], groups[i]) ;
			
			this.schedulerUtils.pauseJob(task);
		}
		// 数据库表中的状态
		this.mapper.updateBatchStatusByJobId(jobIds, SchedulerConst.ScheduleStatus.PAUSE.getValue());
	}

	@Transactional
	@Override
	public void resume(Long[] jobIds, String[] groups) {
		for(int i=0; i<jobIds.length; i++) {
			SchedulerTask task = new SchedulerTask(jobIds[i], groups[i]) ;
			
			this.schedulerUtils.resumeJob(task);
		}
		// 数据库表中的状态
		this.mapper.updateBatchStatusByJobId(jobIds, SchedulerConst.ScheduleStatus.NORMAL.getValue());
	}

	@Override
	public void deleteJob(Long[] jobIds, String[] groups) {
		for(int i=0; i<jobIds.length; i++) {
			SchedulerTask task = new SchedulerTask(jobIds[i], groups[i]) ;
			
			this.schedulerUtils.resumeJob(task);
		}
		// 删除数据库表中的数据
		super.deleteByIds(Arrays.asList(jobIds)) ;
	}

}
